package com.ruoyi.wecom.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import com.ruoyi.business.domain.vo.UserChatGroupStatisticVO;
import com.ruoyi.business.domain.vo.wecom.admin.RecentActiveCustomerFollowerVO;
import com.ruoyi.business.domain.vo.wecom.admin.RecentActiveCustomerVO;
import com.ruoyi.business.domain.vo.wecom.admin.RecentActiveGroupVO;
import com.ruoyi.business.domain.vo.wecom.admin.TbWecomMsgArchiveVO;
import com.ruoyi.business.service.wecom.ITbWecomMsgArchiveService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.page.TableDataInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.YearMonth;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;

@Validated
@Api(value = "企微会话存档消息列表", tags = {"企微会话存档消息列表查询"})
@RequiredArgsConstructor
@RestController
@RequestMapping("/wecom/msg/archive")
public class WecomMsgArchiveController extends BaseController {


    @Resource
    private ITbWecomMsgArchiveService tbWecomMsgArchiveService;

    /**
     * 会话存档消息列表
     */
    @ApiOperation("分页查询企微聊天记录")
    @SaCheckPermission("wecom:msg:archive:page")
    @GetMapping("/sys-page")
    public TableDataInfo<TbWecomMsgArchiveVO> sysPageQuery(
        @ApiParam("发送方客户id") @RequestParam(required = false) String fromUserId,
        @ApiParam("接收方客户id") @RequestParam(required = false) String toUserId,
        @ApiParam("群聊id") @RequestParam(required = false) String chatId,
        @ApiParam("筛选开始时间") @RequestParam(required = true) Long beginTime,
        @ApiParam("筛选结束时间") @RequestParam(required = true) Long endTime,
        PageQuery pageQuery) {
        return tbWecomMsgArchiveService.sysPage(fromUserId, toUserId, chatId, beginTime, endTime, pageQuery);
    }

    // 群聊检索 最近活跃的群聊列表-分页查询
    @ApiOperation("群聊检索-最近活跃的群聊列表-分页查询")
    @GetMapping("/recent-active-groups")
    @SaCheckPermission("wecom:msg:recent:active:groups")
    public TableDataInfo<RecentActiveGroupVO> sysRecentActiveGroups(
        @ApiParam("群聊名称") @RequestParam(required = false) String chatName,
        @ApiParam("客户Id") @RequestParam(required = false) String externalUserid,
        @ApiParam("筛选开始时间") @RequestParam(required = false) Long beginTime,
        @ApiParam("筛选结束时间") @RequestParam(required = false) Long endTime,
        PageQuery pageQuery) {
        return tbWecomMsgArchiveService.sysRecentActiveGroups(chatName, externalUserid, beginTime, endTime, pageQuery);
    }

    // 客户检索 最近活跃的客户列表-分页查询
    @ApiOperation("客户检索-最近活跃的客户列表-分页查询")
    @GetMapping("/recent-active-customer")
    @SaCheckPermission("wecom:msg:recent:active:customer")
    public TableDataInfo<RecentActiveCustomerVO> sysRecentActiveCustomers(
        @ApiParam("客户名称") @RequestParam(required = false) String name,
        @ApiParam("筛选开始时间") @RequestParam(required = false) Long beginTime,
        @ApiParam("筛选结束时间") @RequestParam(required = false) Long endTime,
        PageQuery pageQuery) {
        return tbWecomMsgArchiveService.sysRecentActiveCustomers(name, beginTime, endTime, pageQuery);
    }


    @ApiOperation("群聊检索-最近活跃的客户客服列表-分页查询")
    @GetMapping("/recent-active-customer-follower")
    @SaCheckPermission("wecom:msg:recent:active:customer:follower")
    public TableDataInfo<RecentActiveCustomerFollowerVO> sysRecentServicesByCustomerId(
        @ApiParam("客户Id") @RequestParam(required = true) String externalUserid,
        @ApiParam("客服名称") @RequestParam(required = false) String name,
        @ApiParam("筛选开始时间") @RequestParam(required = false) Long beginTime,
        @ApiParam("筛选结束时间") @RequestParam(required = false) Long endTime,
        PageQuery pageQuery) {
        return tbWecomMsgArchiveService.selectRecentServicesByCustomerId(externalUserid, name, beginTime, endTime, pageQuery);
    }

    /**
     * 获取客户群活跃统计
     */
    @ApiOperation("koc用户活跃统计")
    @GetMapping("/customerGroupActiveStats")
    public TableDataInfo<UserChatGroupStatisticVO> getCustomerGroupActiveStats(
        @ApiParam("用户id") @RequestParam(required = true) Long userId,
        @ApiParam("kocDate") @RequestParam(required = true) String kocDate,
        PageQuery pageQuery) {
        long beginTime = getFirstDayOfMonthTimestamp(kocDate);
        long endTime = getFirstDayOfNextMonthTimestamp(kocDate);
        // 获取当前毫秒级时间戳 如果当前时间戳小于 endTime 则 endTime 为当前毫秒级时间戳
        long currentTime = System.currentTimeMillis();
        if (currentTime < endTime) {
            endTime = currentTime;
        }
        return tbWecomMsgArchiveService.getCustomerGroupActiveStatsPage(userId, beginTime, endTime, pageQuery);
    }


    /**
     * 获取指定年月当月1号 00:00:00 的时间戳（毫秒）
     */
    public static long getFirstDayOfMonthTimestamp(String yearMonth) {
        // 解析年月字符串
        YearMonth ym = YearMonth.parse(yearMonth, DateTimeFormatter.ofPattern("yyyy-MM"));
        // 获取当月1号的 LocalDateTime（00:00:00）
        LocalDateTime firstDay = ym.atDay(1).atStartOfDay();
        // 转换为时间戳（毫秒）
        return firstDay.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
    }

    /**
     * 获取指定年月下个月1号 00:00:00 的时间戳（毫秒）
     */
    public static long getFirstDayOfNextMonthTimestamp(String yearMonth) {
        // 解析年月字符串
        YearMonth ym = YearMonth.parse(yearMonth, DateTimeFormatter.ofPattern("yyyy-MM"));
        // 获取下个月
        YearMonth nextMonth = ym.plusMonths(1);
        // 获取下个月1号的 LocalDateTime（00:00:00）
        LocalDateTime firstDayOfNextMonth = nextMonth.atDay(1).atStartOfDay();
        // 转换为时间戳（毫秒）
        return firstDayOfNextMonth.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
    }

}
